package com.code.template;

import java.util.Collection;
import java.util.List;





import com.code.util.CodeUtil;
import com.code.util.StrUtil;

public class TypeFileTemplate {
	private static StringBuilder EMPTY = new StringBuilder(0);
	private AbstractTypeData bean;

	public TypeFileTemplate(AbstractTypeData abstractCodeData) {
		this.bean = abstractCodeData;
	}

	public String toCode() {
		int i = 0;
		return new StringBuilder().append(packageDeclare(i))
				.append(importDeclares(i)).append(typeDeclareOpen(i++))
				.append(attributeDeclares(i)).append(methodDeclares(i))
				.append(typeDeclareClose(--i)).toString();
	}

	private StringBuilder packageDeclare(int indent) {
		String package1 = bean.getPackage();
		if (StrUtil.isEmpty(package1))
			return EMPTY;
		return new StringBuilder(CodeUtil.newTab(indent)).append(package1)
				.append("\n\n");
	}

	private StringBuilder importDeclares(int indent) {
		Collection<String> importTypes = bean.getImportTypes();
		if (importTypes.isEmpty())
			return EMPTY;

		return new StringBuilder(CodeUtil.newTab(indent)).append(
				CodeUtil.getImportDeclaresByTypes(importTypes)).append("\n");
	}

	private StringBuilder typeDeclareOpen(int indent) {
		return new StringBuilder(CodeUtil.newTab(indent))
				.append(bean.getTypeVisibilty())
				.append(bean.getTypeModifiers()).append(bean.getType())
				.append(bean.getTypeName()).append(bean.getSuperTypeName())
				.append("{\n");
	}

	private StringBuilder typeDeclareClose(int indent) {
		return new StringBuilder(CodeUtil.newTab(indent)).append(bean
				.getTypeDeclareClose());
	}

	private StringBuilder methodDeclares(int indent) {
		List<String> methods = bean.getMethodsDeclare();
		if (methods.isEmpty())
			return EMPTY;
		StringBuilder b = new StringBuilder();
		for (String method : methods) {
			String newTab = CodeUtil.newTab(indent);
			b.append(newTab)
					.append(StrUtil.replace(method, "\n", "\n" + newTab))
					.append("\n");
		}
		b.append("\n");
		return b;
	}

	private StringBuilder attributeDeclares(int indent) {
		List<String> attrs = bean.getAttributesDeclare();
		if (attrs.isEmpty())
			return EMPTY;
		StringBuilder b = new StringBuilder();
		for (String attr : attrs) {
			b.append(CodeUtil.newTab(indent)).append(attr).append("\n");
		}
		b.append("\n");
		return b;
	}
}
